<?php
/**
 * 产品供应商（基础）模型
 * (model)
 */
namespace App\Models\Product;

use App\Models\Basics\Supplier;
use Illuminate\Database\Eloquent\Relations\Pivot;

class ProductSupplier extends Pivot
{
    protected $table = 'product_supplier';

    /**
     * 标识 ID 是否自增。
     * @var bool
     */
    public $incrementing = true;

    public $timestamps = false;

    //是否默认
    public static $_status = [
        0 => '否',
        1 => '是',
    ];

    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    public function supplier(){
        return $this->belongsTo(Supplier::class,'supplier_id');
    }

    public static function modifyDefaultPuSupplier($id,$pSkuId){
        return self::query()
            ->where('id','<>',$id)
            ->where('psku_id',$pSkuId)
            ->update(['status' => 0]);
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model){
            if($model->status == 1){
                throw new \Exception('默认供应商勿删除');
            }
        });
    }

    /**
     * 采购计划确认时需按指定SKU去选择采购供应商
     * 获取关联产品的所有供应商
     * @param $pSkuId
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
     */
    public static function getSupplierOptionBySku($pSkuId){
        return self::query()
            ->with('supplier')
            ->where('psku_id',$pSkuId)
            ->get()
            ->map(function ($item){
                return collect(['supplier_id' => $item->supplier->id ?? '','supplier_name' => $item->supplier->name ?? '']);
            })
            ->pluck('supplier_name','supplier_id');
    }
}
